# -*- coding: utf-8 -*-
# @Time    : 2018-05-22 21:08
# @Author  : Yang Feng
# @Email   : yangfeng@bbdservice.com
# @File    : Ind_LongestContinuousOverdueMon_2YrCheck.py
# @Software: PyCharm

'''eof
name:申请人2年内单笔信贷最长连续逾期月份数校验
code:Ind_LongestContinuousOverdueMon_2YrCheck
tableName:
columnName:
groups:准入>个人征信
dependencies:IC
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import json
import re
import datetime
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', None, 'null', '/', 'Null']

def FormatData(tableName):
    try:
        icr = json.loads(IC[0]["icr"])[tableName]
        return icr if isinstance(icr, list) and len(icr) > 0 else [{}]
    except:
       return [{}]


def ConvertDataType(dataValue, dataType):
    returnData = None
    if dataType == 'float':
        try:
            returnData = float(dataValue) if float(dataValue) >= 0 else None
        except:
            returnData = None
    elif dataType == 'None':
        returnData = 0 if dataValue is None else dataValue
    return returnData


def IndLongestContinuousOverdueMon2YrCheckPre(*arg):
    try:
        # 两年之前(year*12+month)
        monthToday = datetime.datetime.now().year * 12 + datetime.datetime.now().month
        monthTwoyearsAgo = (datetime.datetime.now().year - 2) * 12 + datetime.datetime.now().month
        dk = 0
        icrLoanInfo002LoanList = FormatData(arg[0])
        # 逾期记录明细
        icrLatest5YearOverdueDetailList = FormatData(arg[1])
        if icrLoanInfo002LoanList == [{}] and icrLatest5YearOverdueDetailList == [{}]:
            dk = None
        else:
            month24Max = []
            # 取24个月还款状态最大数
            for icrLoanInfo002Loan in icrLoanInfo002LoanList:
                try:
                    latest24StateLil = icrLoanInfo002Loan.get('Latest24State')
                    if latest24StateLil in null_type_list:
                        month24Max.append(None)
                        continue
                    latest24StateLilSub = latest24StateLil[::-1]
                    latest24StateList = filter(lambda x: x >= 1 and x <= 7, map(float, re.compile("\d").findall(latest24StateLilSub)))
                    if arg[0] == "ICRStdLoancardInfo002*Std":
                        latest24StateList = map(lambda x: x - 2, filter(lambda x:x > 2, latest24StateList))
                    if len(latest24StateList) == 0:
                        month24Max.append("None")
                    else:
                        month24Max.extend(latest24StateList)
                except:
                    month24Max.append(None)
                    continue
            # 取2年内持续逾期最大数
            for icrLatest5YearOverdueDetail in icrLatest5YearOverdueDetailList:
                try:
                    month = re.compile(r'\D+').sub('', icrLatest5YearOverdueDetail.get('Month'))
                    if month in null_type_list:
                        month24Max.append(None)
                        continue
                    monthFact = float(month[:4]) * 12 + float(month[4:6]) if float(month[4:6]) <= 12 else float(month[4:5])
                    if monthFact > monthToday:
                        month24Max.append(None)
                        continue
                    if monthFact > monthTwoyearsAgo:
                        lastMonths = ConvertDataType(icrLatest5YearOverdueDetail.get('LastMonths'), 'float')
                        lastMonths = "None" if lastMonths < 1 or lastMonths > 7 else lastMonths
                        if arg[0] == "ICRStdLoancardInfo002*Std" and lastMonths is not None:
                            if lastMonths > 2:
                                month24Max.append(lastMonths - 2)
                            else:
                                month24Max.append("None")
                        else:
                            month24Max.append(lastMonths)
                    else:
                        month24Max.append("None")
                except:
                    month24Max.append(None)
                    continue
            month24MaxNotNone = filter(lambda x: x is not None, month24Max)
            month24MaxNotNoneStr = filter(lambda x: x != 'None', month24MaxNotNone)
            if len(month24MaxNotNone) == 0:
                dk = None
            elif len(month24MaxNotNoneStr) == 0:
                dk = 0
            else:
                dk = int(max([0] if map(float, month24MaxNotNoneStr) == [] else map(float, month24MaxNotNoneStr)))
        return dk
    except:
        return None


def IndLongestContinuousOverdueMon2YrCheck():
    # 贷款逾期信息
    dk = IndLongestContinuousOverdueMon2YrCheckPre(*("ICRLoanInfo002*Loan", "ICRLatest5YearOverdueDetail*Loan"))
    # 贷记卡逾期信息
    djk = IndLongestContinuousOverdueMon2YrCheckPre(*("ICRLoancardInfo002*Card", "ICRLatest5YearOverdueDetail*Card"))
    # 准贷记卡逾期信息
    zdjk = IndLongestContinuousOverdueMon2YrCheckPre(*("ICRStdLoancardInfo002*Std", "ICRLatest5YearOverdueDetail*Std"))
    if zdjk is None and djk is None and dk is None:
        return u"缺失值"
    return max(zdjk if zdjk is not None else 0, djk if djk is not None else 0, dk if dk is not None else 0)


result = IndLongestContinuousOverdueMon2YrCheck()